package cn.hbads.test.executor;

import cn.hbads.support.id.IdUtil;
import cn.hbads.test.context.TaskContextManager;
import cn.hbads.test.context.TaskMonitor;
import cn.hbads.test.task.ExecuteTask;

import java.util.ArrayList;
import java.util.List;

/**
 * <b> 单链式任务执行器接口 </b>
 *
 * @author : yvvb
 * @date : 2025/5/11
 */
public class ChainTaskExecutor extends AbstractTaskExecutor {

    private ExecuteStatus executeStatus = ExecuteStatus.BUILD;
    ;
    private List<ExecuteTask> tasks = new ArrayList<>();

    public ChainTaskExecutor(TaskContextManager taskContextManager, TaskMonitor taskMonitor) {
        super(taskContextManager, taskMonitor);
    }

    public ChainTaskExecutor(String batchNo, TaskContextManager taskContextManager, TaskMonitor taskMonitor) {
        super(taskContextManager, taskMonitor);
    }

    @Override
    public String prepare() {
        final var batchNo = IdUtil.uuidStr();
        this.executeStatus = ExecuteStatus.PREPARE;
        taskContextManager.initContext(batchNo, this.tasks);
        taskMonitor.startBatchTaskList(tasks);
        return batchNo;
    }

    @Override
    public synchronized void executeTasks() {
        String batchNo = prepare();
        this.executeStatus = ExecuteStatus.EXECUTING;
        for (ExecuteTask task : tasks) {
            if (!task.execute(taskContextManager, taskMonitor)) {
                taskMonitor.interruptBatchTasksExecute(batchNo, task.getTaskName());
                this.executeStatus = ExecuteStatus.PAUSE;
            }
        }
        taskMonitor.successEndBatchTaskExecute(batchNo);
        this.executeStatus = ExecuteStatus.END;
    }

    public synchronized ChainTaskExecutor next(ExecuteTask task) {
        if (this.executeStatus.equals(ExecuteStatus.BUILD)) {
            tasks.add(task);
            return this;
        } else {
            throw new IllegalStateException("Executor status is not BUILD");
        }
    }
}
